import request from './request.js';
import api from './appOnLaunch.js';
import apiurl from './apiUrl.js';
import {
	getStorageSync,
	setStorageSync
} from './cache.js';
import event from './event.js';
import $const from './const.js';
import $store from '../store/index.js';
import Vue from 'vue';
import siteInfo from 'siteInfo';
const storageKey = '_USER_ACCESS_TOKEN';
const useropenId = '_USER_OPENID'

let userInfo = null;

export default {
	getUserInfoResolve: null,
	getUserInfoReject: null,
	getAccessToken(options) {
		options = options || {};
		if (typeof options.cacheOnly === 'undefined') {
			options.cacheOnly = false;
		}
		return new Promise((resolve, reject) => {
			let accessToken = getStorageSync(storageKey);
			if (accessToken) {
				return resolve(accessToken);
			}
			if (options.cacheOnly) {
				return resolve(accessToken);
			}
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			currentPage.$vm.$store.commit('user/showLoginModal', true);

			/* this.getUserInfoResolve = (userInfoResult) => {
				uni.showLoading({
					mask: true,
					title: '正在登录',
				});
				uni.login({
					scopes: 'auth_user',
					success(loginResult) {
						 ;
						if (getApp().globalData.canIUseGetUserProfile) {
							const data = {
								encryptedData: userInfoResult.encryptedData,
								iv: userInfoResult.iv,
								rawData: userInfoResult.rawData,
								signature: userInfoResult.signature,
								code: loginResult.code,
							};
							console.log(6666666);
						}else{
							const data = {
								encryptedData: userInfoResult.detail.encryptedData,
								iv: userInfoResult.detail.iv,
								rawData: userInfoResult.detail.rawData,
								signature: userInfoResult.detail.signature,
								code: loginResult.code,
							};
							console.log(7777777);
						}
						
						request({
							url: api.passport.login,
							method: 'post',
							data: data,
						}).then(response => {
							uni.hideLoading();
							if (response.code === 0) {
								event.trigger($const.EVENT_USER_LOGIN);
								setStorageSync(storageKey, response.data.access_token);
								request({
									url: api.share.new_apply_status,
								}).then(res => {
									if (res.data.status == 1) {} else {
										request({
											url: api.share.apply,
											method: 'post'
										}).then(response => {
											console.log(response);
										}).catch(() => {
								
										});
									}
								})
								return resolve(response.data.access_token);
							} else {
								return reject(response.msg);
							}
						}).catch(e => {
							uni.hideLoading();
							reject(e);
						});
					},
				});
			}; */
			if (getApp().globalData.canIUseGetUserProfile) {
				this.getUserInfoResolve = (userInfoResult) => {

					let nes = uni.getStorageSync('_USER_OPENID')
					// console.log(nes, 548754444444444444444);
					uni.showLoading({
						mask: true,
						title: '正在登录',
					});
					uni.login({
						scopes: 'auth_user',
						success(loginResult) {
							const data = {
								encryptedData: userInfoResult.encryptedData,
								iv: userInfoResult.iv,
								rawData: userInfoResult.rawData,
								signature: userInfoResult.signature,
								code: loginResult.code,
								openId: getStorageSync('_USER_OPENID'),
								unionId: getStorageSync('_USER_UNIONID'),
							};
							// console.log(data, 6666666);
							request({
								url: api.passport.login,
								method: 'post',
								data: data,
							}).then(response => {
								uni.hideLoading();
								if (response.code === 0) {
									event.trigger($const.EVENT_USER_LOGIN);
									setStorageSync(storageKey, response.data.access_token);
									request({
										url: api.share.new_apply_status,
									}).then(res => {
										if (res.data.status == 1) {} else {
											request({
												url: api.share.apply,
												method: 'post'
											}).then(response => {
												// console.log(response);
											}).catch(() => {

											});
										}
									})
									return resolve(response.data.access_token);
								} else {
									return reject(response.msg);
								}
							}).catch(e => {
								uni.hideLoading();
								reject(e);
							});
						},
					});
				};
			} else {
				this.getUserInfoResolve = (userInfoResult) => {
					uni.showLoading({
						mask: true,
						title: '正在登录',
					});
					uni.login({
						scopes: 'auth_user',
						success(loginResult) {
							const data = {
								encryptedData: userInfoResult.detail.encryptedData,
								iv: userInfoResult.detail.iv,
								rawData: userInfoResult.detail.rawData,
								signature: userInfoResult.detail.signature,
								code: loginResult.code,
								openId: getStorageSync('_USER_OPENID'),
								unionId: getStorageSync('_USER_UNIONID'),
							};
							request({
								url: api.passport.login,
								method: 'post',
								data: data,
							}).then(response => {
								uni.hideLoading();
								if (response.code === 0) {
									event.trigger($const.EVENT_USER_LOGIN);
									setStorageSync(storageKey, response.data.access_token);
									request({
										url: api.share.new_apply_status,
									}).then(res => {
										if (res.data.status == 1) {} else {
											request({
												url: api.share.apply,
												method: 'post'
											}).then(response => {
												// console.log(response);
											}).catch(() => {

											});
										}
									})
									return resolve(response.data.access_token);
								} else {
									return reject(response.msg);
								}
							}).catch(e => {
								uni.hideLoading();
								reject(e);
							});
						},
					});
				};
			}

			this.getUserInfoReject = (e) => {
				// console.log(e, 3535353373333333333);
				reject(e);
			};
		});
	},
	getInfo(options) {
		options = options || {};
		if (typeof options.refresh === 'undefined') {
			options.refresh = false;
		}
		return new Promise((resolve, reject) => {
			if (options.refresh) {
				userInfo = null;
			}
			if (userInfo) {
				return resolve(userInfo);
			}
			this.godshare()
			this.getAccessToken().then(accessToken => {
				uni.showNavigationBarLoading();
				request({
					url: api.user.user_info,
				}).then(response => {
					uni.hideNavigationBarLoading();
					if (response.code === 0) {
						userInfo = JSON.parse(JSON.stringify(response.data));
						event.trigger($const.EVENT_USER_REGISTER, userInfo);
						if (typeof userInfo.register !== 'undefined') {
							let register = userInfo.register;
							if (register.coupon_list) {
								let coupon = {
									list: register.coupon_list,
									type: 'register'
								};
								$store.dispatch('page/actionSetCoupon', coupon);
							}
						}
						return resolve(userInfo);
					} else {
						return reject(response.msg);
					}
				}).catch(e => {
					uni.hideNavigationBarLoading();
					return reject(e);
				});
			}).catch(e => {
				return reject(e);
			});
		});
	},
	isLogin() {
		if ($store && $store.state.user && $store.state.user.accessToken) return true;
		return !!getStorageSync(storageKey);
	},
	loginByToken(token) {
		setStorageSync(storageKey, token);
	},
	silentLogin() {
		let that = this
		uni.login({
			success: function(loginRes) {
				request({
					url: api.passport.login,
					method: 'post',
					data: {
						code: loginRes.code
					},
				}).then(response => {
					// console.log(response, 444444444444444444);
					if (response.code === 0) {
						uni.setStorageSync(storageKey, response.data.access_token);
						// 10.18 
						if (response.data.userinfo) {
							uni.setStorageSync('_USER_OPENID', response.data.userinfo.username)
							uni.setStorageSync('_USER_UNIONID', response.data.userinfo.unionId)
						}
						$store.dispatch('user/accessToken');
					} else {
						uni.setStorageSync('_USER_OPENID', response.data.userinfo.username)
						uni.setStorageSync('_USER_UNIONID', response.data.userinfo.unionId)
						$store.dispatch('user/accessToken');
					}
					that.godshare()
				});
			}
		});
	},
	godshare() {
		// if ($store.state.user.accessToken === '' || $store.state.user.accessToken === null) {
		// 	$store.dispatch('user/accessToken');
		// 	return;
		// }
		let mallid = $store.state.user.mallid
		let targoodsid = $store.state.user.targoodsid
		let useridres = $store.state.user.useridres
		let mallurl = siteInfo.apiroot + '?_mall_id=' + mallid + '&r='
		let url = api.gold.index
		let pdata = {
			type: 5,
			targetid: targoodsid,
			userid: useridres
		}
		if (mallid > 1) {
			url = mallurl + apiurl.gold.index
		}
		if (useridres && useridres != 0 && targoodsid && targoodsid != 0) {
			request({
				url: url,
				data: pdata
			}).then(res => {
				if (res.data.isdone >= 0) {} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			});
		}
	}
}
